package com.lihepeng.leecode.linkedList;

import org.junit.Test;

/**
 * 给定一个排序链表，删除所有含有重复数字的节点，只保留原始链表中 没有重复出现 的数字。
 * <p>
 * 示例 1:
 * <p>
 * 输入: 1->2->3->3->4->4->5
 * 输出: 1->2->5
 * 示例 2:
 * <p>
 * 输入: 1->1->1->2->3
 * 输出: 2->3
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Solution82 {
    // 使用双指针方法操作
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dumpNode = new ListNode(-1);
        dumpNode.next = head;
        ListNode slow = dumpNode;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            if (slow.next.value != fast.next.value) {
                slow = slow.next;
                fast = fast.next;
            } else {
                while (fast != null && fast.next != null && slow.next.value != fast.next.value) {
                    fast = fast.next;
                }
                slow.next = fast.next;
                fast = fast.next;
            }

        }
        return dumpNode.next;
    }

    public String showList(ListNode head) {
        StringBuffer sb = new StringBuffer();
        while (head != null) {
            sb.append(head.value);
            head = head.next;
            sb.append(">");
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

    /**
     * 删除链表中的重复元素 2021年3月25日 每日一题
     * @param head
     * @return
     */
    public ListNode deleteDuplicates01(ListNode head) {
        if (head ==null){
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode cur = dummy;
        while(cur.next!=null && cur.next.next!=null){
            if (cur.next.value==cur.next.next.value){
                int x = cur.next.value;
                while(cur.next!=null && cur.next.value == x){
                    cur.next=cur.next.next;
                }
            }else {
                cur = cur.next;
            }
        }
        return dummy.next;
    }

    @Test
    public void runTest() {
        ListNode head = new ListNode(0);
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(4);
        head.next = n1;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        String s = showList(head);
        System.out.println(s);
        ListNode listNode = deleteDuplicates(head);
        System.out.println(showList(listNode));


    }

}
